// index.js
Page({
	data: {
		curr_nfcv_compare: '',
		curr_nfcv_var: '请读取NFC-V卡',
	},

	nfcRead() {
		var that = this;
		const adapter = wx.getNFCAdapter();
		console.log("获取NFC实例", adapter)
		adapter.onDiscovered(res => {
			console.log("读取到卡片了", res);
			let tagId = res.id;
			const data = new Uint8Array(tagId)
			// console.log(data)
			// console.log("获取到tagID：", tagId);
			// console.log("获取到techs：", res.techs);
			if (res.techs.includes(adapter.tech.nfcV)) {
				// console.log('发现' + adapter.tech.nfcV + '卡');
				let str = ""
				data.forEach(e => {
					let item = e.toString(16)
					if (item.length == 1) {
						item = '0' + item
					}
					item = item.toUpperCase()
					// console.log(item)
					str += item
				})
				console.log("获取：", str);
				var get_perv_var = that.data.curr_nfcv_var
				if (get_perv_var == str) {
					that.play_muise('erro.mp3');
					var curr_nfcv_compare = '重复扫描'
				} else {
					that.play_muise('succ.mp3');
					var curr_nfcv_compare = ''
				}
				that.setData({
					curr_nfcv_var: str,
					curr_nfcv_compare: curr_nfcv_compare,
				})

			} else {
				that.play_muise('nocard.mp3');
				console.log('没发现卡');
				wx.showToast({
					title: '卡片类型有误！',
					icon: 'error'
				})
			}
		})
		adapter.startDiscovery({
			success: function (res) {
				console.log('startDiscovery:', res);
			},
			fail(err) {
				console.log('failed to discover:', err)
				if (!err.errCode) {
					wx.showToast({
						title: '请检查NFC功能是否正常!',
						icon: 'none'
					})
					that.setData({
						curr_nfcv_var: '请检查NFC功能是否正常!',
					})
					return
				}
				switch (err.errCode) {
					case 13000:
						wx.showToast({
							title: '设备不支持NFC!',
							icon: 'none'
						})
						that.setData({
							curr_nfcv_var: '设备不支持NFC!',
						})
						break;
					case 13001:
						wx.showToast({
							title: '系统NFC开关未打开!',
							icon: 'none'
						})
						that.setData({
							curr_nfcv_var: '系统NFC开关未打开!',
						})
						break;
					case 13019:
						wx.showToast({
							title: '用户未授权!',
							icon: 'none'
						})
						that.setData({
							curr_nfcv_var: '用户未授权!',
						})
						break;
					case 13010:
						wx.showToast({
							title: '未知错误!',
							icon: 'none'
						})
						that.setData({
							curr_nfcv_var: '未知错误',
						})
						break;
				}
			}
		})
	},


	play_muise(muise_name) {
		const innerAudioContext = wx.createInnerAudioContext({
			useWebAudioImplement: true // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
		})
		// 不能使用本地mp3,需要远程网址的。
		innerAudioContext.src = 'https://x.quhuichang.cn/imagex/' + muise_name
		innerAudioContext.play() // 播放
	},


	onLoad: function (options) {

		this.nfcRead();

	},



})